#include "rel.h"
#define MAX_RETRANSMITS 4

/**
 * Creates the thread that checks for responses from the partner application
 */

void createTimerThread() {
  
  // Create Thread
  pthread_t timerThread;
  pthread_create (&timerThread, NULL, checkForResponse, NULL);
  
}

/** 
 * Checks for responses approximately every three seconds.  If no response is
 * found within the past three seconds, then the last message will be retransmitted.
 */

void * checkForResponse () {  
  
  // Variables to hold current time and time difference
  time_t currentTime;
  time_t deltaTime;
  
  if (debug) {
    printf("\nResponse timeout thread has started\n");
  }
  
  
  // Loop while still sending messages
  while (timerOn) {   
    
    // Sleep for the allotted time limit
    sleep(1);
        
    // Get current time and calculate time between now and last response
    currentTime = time(NULL);
    deltaTime = currentTime - lastResponseTime;      
    
    // If more than the allotted time has elapsed without a response, perform
    // the actions below
    if ( deltaTime > 1 ) {
      void * ptr = (void *) &deltaTime;
      long * longPtr = (long *) ptr;
      
      printf("\n%ld seconds have passed with no response. Retransmitting...", *longPtr);        
      
      if ( numRetransmits < MAX_RETRANSMITS ) {
      
        // Lock numRetransmits and sendMessageBuffer
        pthread_mutex_lock ( &mutexLock );
        
        numRetransmits++;   
        
        // UNLock sendMessageBuffer
        pthread_mutex_unlock ( &mutexLock );  
        
        // If this is the sender
        if (sender){       
          if (debug) {
            printf("\nRECEIVER ADDRESS: %s\n", ipAddress);
            printf("RECEIVER PORT: %d\n\n", receiverPort);           
          }
          // Lock numRetransmits and sendMessageBuffer
        	pthread_mutex_lock ( &mutexLock );
          
          // Send last message again
          sendUDP (ipAddress, receiverPort, socketfd, sendMessageBuffer, sendMessageSize);
       	 	
       	 	// Lock numRetransmits and sendMessageBuffer
       		pthread_mutex_unlock ( &mutexLock );
        }
        
        // Receiver Case
        else {
          if (debug) {
            printf("\nSENDER ADDRESS: %s\n", ipAddress);
            printf("SENDER PORT: %d\n\n", senderPort);
          }
          
          // Lock numRetransmits and sendMessageBuffer
 		      pthread_mutex_lock ( &mutexLock );
                    
          // Send last message again
          sendUDP (ipAddress, senderPort, socketfd, sendMessageBuffer, sendMessageSize);
  				
  				// Lock numRetransmits and sendMessageBuffer
	        pthread_mutex_unlock ( &mutexLock );
  
        }
        
              
      } 
       
      // If there have been three retransmissions of the same message,
      // close the program.
      else {
        if(!sender && (!successfulTransfer)) {
          printf("\nGoing to remove %s due to failure.\n", fileName);
          remove(fileName);
        }
        printf("\n\nMaximum retransmissions Reached.");
        printf("\nYou may be experiencing problems. Closing now.\n");
        exit(1);
      }
    
    } // End If delta > 3 sec
    
  } // End Infinite Loop
  
}